package com.qf.mybatis;

import com.qf.mybatis.mapper.UserMapper;
import com.qf.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HelloMybatis {
    @Test
    public void demo1() throws IOException {
        //获取读取MyBatis配置文件的流对象
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //构建SQLSession连接对象的工厂
        SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(is);
        //通过工厂获得连接对象
        SqlSession sqlSession = ssf.openSession();
        //通过连接对象获得接口实现类对象
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        User user=mapper.selectUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

    SqlSession sqlSession = null;
    @Before
    public void doBefore() throws IOException {
        //1.获得读取MyBatis配置文件的流对象
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

        //2.构建SqlSession连接对象的工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂获得连接对象
        sqlSession = factory.openSession();
    }
    @After
    public void doAfter(){
        sqlSession.close();
    }
    @Test
    public void demo2(){
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUserByIdAndPwd(1, "12345");
        System.out.println(user);

    }
    @Test
    public void test4(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map values=new HashMap();
        values.put("myId",2);
        values.put("myPwd","234");
        User user=mapper.selectUserByIdAndPwd_map(values);
        System.out.println(user);
    }
    @Test
    public void test5(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = new User();
        user1.setName("zs");
        user1.setPassword("12345");
        User user = mapper.selectUserByUserInfo(user1);
        System.out.println(user);
    }
    @Test
    public void test6(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        String keyword="%z%";
        List<User>list =mapper.selectUserByKeyWord(keyword);
        System.out.println(list);

    }



}
